package com.sd365.permission.centre.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;

import com.github.pagehelper.PageHelper;

import com.sd365.common.core.annotation.stuffer.CommonFieldStuffer;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.annotation.stuffer.MethodTypeEnum;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BusinessErrorCode;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.common.util.StringUtil;
import com.sd365.permission.centre.dao.mapper.DictionaryMapper;
import com.sd365.permission.centre.entity.Dictionary;
import com.sd365.permission.centre.pojo.dto.CompanyDTO;
import com.sd365.permission.centre.pojo.dto.DictionaryDTO;
import com.sd365.permission.centre.pojo.dto.DictionaryTypeDTO;
import com.sd365.permission.centre.pojo.dto.OrganizationDTO;
import com.sd365.permission.centre.pojo.query.DictionaryQuery;
import com.sd365.permission.centre.service.DictionaryService;
import com.sd365.permission.centre.service.exception.UserCentreExceptionCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import tk.mybatis.mapper.entity.Example;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @class DictionaryServiceImpl
 * @classdesc
 * @author Administrator
 * 业务层:对数据库进行操作在此处,RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback
 * @date 2020-10-18  18:00
 * @version 1.0.0
 * @see
 * @since
 */
/**
 * @author wujiandong
 * @date 2022/08/17 14:17
 * @version 1.0.9
 * @description add方法 参数的tenantId、orgId、companyId等属性进行填充
 */
@Service
@Component
public class DictionaryServiceImpl extends AbstractBaseDataServiceImpl implements DictionaryService {
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private IdGenerator idGenerator;


    @CommonFieldStuffer(methodType = MethodTypeEnum.ADD)
    @Override
    public Boolean add(@Valid @NotNull DictionaryDTO dictionaryDTO) {
        Dictionary dictionary=BeanUtil.copy(dictionaryDTO,Dictionary.class);
        dictionary.setValue(dictionaryDTO.getName());
        dictionary.setId(idGenerator.snowflakeId());
        dictionary.setDictionaryTypeId(dictionaryDTO.getDictionaryTypeDTO().getId());
        if(dictionaryMapper.selectByName(dictionary.getName()).size() > 0){
            return false;
        }
        super.baseDataStuff4Add(dictionary);
        return dictionaryMapper.insert(dictionary)>0;
    }

    @Override
    public Boolean remove(@Valid @NotNull Long id, @Valid @NotNull Long version) {
        Example example=new Example(Dictionary.class);
        example.createCriteria().andEqualTo("id",id).andEqualTo("version",version);
        return dictionaryMapper.deleteByExample(example)>0;
    }

    @Override
    public Boolean modify(@Valid @NotNull DictionaryDTO dictionaryDTO) {
        Dictionary dictionary= BeanUtil.copy(dictionaryDTO, Dictionary.class);

        dictionary.setValue(dictionaryDTO.getName());

        if(dictionaryMapper.selectByName(dictionary.getName()).size() > 0){
            return false;
        }
        super.baseDataStuff4Updated(dictionary);
        return dictionaryMapper.updateDictionary(dictionary)>0;
    }

    @CommonFieldStuffer(methodType = MethodTypeEnum.QUERY)
    @Override
    public List<DictionaryDTO> commonQuery(@Valid @NotNull DictionaryQuery dictionaryQuery) {
            if (dictionaryQuery == null) {
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("commonQuery 方法错误"));
            }
            try {
                // po list
                //List<Dictionary> Dictionarys= DictionaryMapper.selectByExample(example);
                Dictionary dictionary = new Dictionary();
                if(StringUtil.isEmpty(dictionary.getName())){
                    dictionary.setName(dictionaryQuery.getName());
                }

                if(dictionaryQuery.getDictionaryCategoryId()!=null && dictionaryQuery.getDictionaryCategoryId()!=0){
                    dictionary.setDictionaryTypeId(dictionaryQuery.getDictionaryCategoryId());
                }


                PageHelper.startPage(dictionaryQuery.getPageNum(), dictionaryQuery.getPageSize());
                List<Dictionary> dictionarys = dictionaryMapper.commonQuery(dictionary);
                Page page = (Page) dictionarys;
                //将总数 页数拷贝到ThreadLocal
                BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(),page.getPages())));


                List<DictionaryDTO> dictionaryDTOS = BeanUtil.copyList(dictionarys, DictionaryDTO.class, (o, o1) -> {
                    // 调用 BeanUtil.copyProperties
                    if (o == null || o1 == null)
                        throw new BeanException("拷贝对象不可以为空", new Exception("copyList 拷贝回调错误"));
                    Dictionary dictionarySource = (Dictionary) o;
                    DictionaryDTO dictionaryDTO = (DictionaryDTO) o1;
                    BeanUtil.copy(dictionarySource.getCompany(), dictionaryDTO.getCompanyDTO(),CompanyDTO.class);
                    BeanUtil.copy(dictionarySource.getOrganization(), dictionaryDTO.getOrganizationDTO(),OrganizationDTO.class);
                    BeanUtil.copy(dictionarySource.getDictionaryType(), dictionaryDTO.getDictionaryTypeDTO(), DictionaryTypeDTO.class);

                });

                return dictionaryDTOS;

            } catch (BeanException ex) {
                throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
            } catch (Exception ex) {
                throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_DICTIONARY_DB_EXCEPTION_CODE, ex);

            }

    }

    @Override
    public DictionaryDTO queryById(@Valid @NotNull Long id) {

        try{
            DictionaryDTO dictionaryDTO= null;
            Dictionary dictionary=dictionaryMapper.selectById(id);
            if(dictionary!=null) {
                dictionaryDTO= BeanUtil.copy(dictionary,DictionaryDTO.class);
                BeanUtil.copy(dictionary.getCompany(),dictionaryDTO.getCompanyDTO(), CompanyDTO.class);
                BeanUtil.copy(dictionary.getOrganization(),dictionaryDTO.getOrganizationDTO(), OrganizationDTO.class);
                BeanUtil.copy(dictionary.getDictionaryType(),dictionaryDTO.getDictionaryTypeDTO(), DictionaryTypeDTO.class);
            }
            return dictionaryDTO;
        }catch (BeanException ex){
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION,ex);
        } catch (Exception ex){
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_CUSTOMER_DB_EXCEPTION_CODE,ex);
        }
    }

    @Override
    public List<DictionaryDTO> queryByTypeId(@Valid @NotNull Long id) {
        if (id == null || id==0) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("commonQuery 方法错误"));
        }
        try {
            // po list
            //List<Dictionary> Dictionarys= DictionaryMapper.selectByExample(example);
            List<Dictionary> dictionarys = dictionaryMapper.selectByTypeId(id);
            //对象转化 po list to dto list
            List<DictionaryDTO> dictionaryDTOS = BeanUtil.copyList(dictionarys, DictionaryDTO.class, new BeanUtil.CopyCallback() {
                @Override
                public void copy(Object o, Object o1) {
                    // 调用 BeanUtil.copyProperties
                    if (o == null || o1 == null)
                        throw new BeanException("拷贝对象不可以为空", new Exception("copyList 拷贝回调错误"));
                    Dictionary dictionarySource = (Dictionary) o;
                    DictionaryDTO dictionaryDTO = (DictionaryDTO) o1;
                    BeanUtil.copy(dictionarySource.getCompany(), dictionaryDTO.getCompanyDTO(),CompanyDTO.class);
                    BeanUtil.copy(dictionarySource.getOrganization(), dictionaryDTO.getOrganizationDTO(),OrganizationDTO.class);
                    BeanUtil.copy(dictionarySource.getDictionaryType(), dictionaryDTO.getDictionaryTypeDTO(),DictionaryTypeDTO.class);
                }
            });
            return dictionaryDTOS;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_DICTIONARY_DB_EXCEPTION_CODE, ex);

        }

    }

    @Override
    public Boolean batchUpdate(@RequestBody DictionaryDTO[] dictionaryDTOS) {
        Assert.noNullElements(dictionaryDTOS,"更新数组不能为空");
        for(DictionaryDTO dictionaryDTO:dictionaryDTOS){
            Dictionary dictionary=BeanUtil.copy(dictionaryDTO,Dictionary.class);
            Example example=new Example(dictionary.getClass());
            dictionary.setVersion(dictionaryDTO.getVersion()+1);
            example.createCriteria().andEqualTo("id",dictionary.getId()).andEqualTo("version",dictionaryDTO.getVersion());;
            super.baseDataStuff4Updated(dictionary);
            int result=dictionaryMapper.updateByExampleSelective(dictionary,example);
            Assert.isTrue(result>0,"没有找到相应id更新记录");
        }
        return true;
    }

    @Override
    public Boolean batchRemove(@RequestBody DictionaryDTO[] dictionaryDTOS) {
        if(dictionaryDTOS.length == 0) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("批量删除参数不可以为空"));
        }
        for(DictionaryDTO dictionaryDTO:dictionaryDTOS){
            Example example=new Example(Dictionary.class);
            example.createCriteria().andEqualTo("id",dictionaryDTO.getId()).andEqualTo("version",dictionaryDTO.getVersion()) ;
            int result=dictionaryMapper.deleteByExample(example);
            if(result<=0) {
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("删除的"+dictionaryDTO.getId()+"记录有匹配到版本"));
            }
        }
        return true;
    }
}
